package com.example.distributedLock;

import com.example.distributedLock.redistools.RedisLockService;
import com.example.thread.Callableimp;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;

/**
 * create by mwh 2021-12-17
 * redis分布式锁
 * redis分布式锁两种方式
 * 1原生jedis+lua脚本
 * 2redisson实现
 *
 * 单机版的测试分布式锁,这个用多线程做并发测试
 *
 **/
@RestController
@RequestMapping("/test")
public class RedisJedisLuaLock {

    @Resource
    RedisLockService redisLockService;
    ExecutorService  executorService = Executors.newFixedThreadPool(5);

    @RequestMapping("/test")
    public void test() throws ExecutionException, InterruptedException {
        Callableimp callableimp =   new Callableimp();
        Lock lock = redisLockService.getLock("test:lock:1", "thread1");
        boolean locked = lock.tryLock(50, TimeUnit.SECONDS);
        if(locked){
            Future<String> future = executorService.submit(callableimp);
        }
        lock.unlock();

        Lock lock2 = redisLockService.getLock("test:lock:2", "thread2");
        boolean locked2 = lock2.tryLock(50, TimeUnit.SECONDS);
        if(locked2){
            Future<String> future2 = executorService.submit(callableimp);
        }
        lock2.unlock();

        Lock lock3 = redisLockService.getLock("test:lock:3", "thread3");
        boolean locked3 = lock3.tryLock(50, TimeUnit.SECONDS);
        if(locked3){
            Future<String> future3 = executorService.submit(callableimp);
        }
        lock3.unlock();

        Lock lock4 = redisLockService.getLock("test:lock:4", "thread4");
        boolean locked4 = lock4.tryLock(50, TimeUnit.SECONDS);
        if(locked4){
            Future<String> future4 = executorService.submit(callableimp);
        }
        lock4.unlock();

        Lock lock5 = redisLockService.getLock("test:lock:5", "thread5");
        boolean locked5 = lock5.tryLock(50, TimeUnit.SECONDS);
        if(locked5){
            Future<String> future5 = executorService.submit(callableimp);
        }
        lock5.unlock();

    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        new RedisJedisLuaLock().test();
    }

}